# -*- coding: utf-8 -*-

from enum import Enum
from datetime import datetime, date
from fastapi import APIRouter, Path, Query, Cookie, Header
from typing import Optional, List
from pydantic import BaseModel, Field


chapter01 = APIRouter()

"""Path Parameters and Number Validations 路径参数和数字验证"""
# 函数的顺序就是路由的顺序
# 路径参数
@chapter01.get('/path/parameters')
def path_params01():
    return {"message": "this is a message"}


@chapter01.get('/path/{parameters}')
def path_params01(parameters: str):
    return {"message": parameters}


class CityName(str, Enum):
    beijing = "beijing china"
    shanghai = "shanghai china"


# 枚举类型参数
@chapter01.get('/enum/{city}')
async def latest(city: CityName):
    if city == CityName.shanghai:
        return {"city_name": city, "confirmed": 1492, "death": 7}
    if city == CityName.beijing:
        return {"city_name": city, "confirmed": 971, "death": 9}
    return {"city_name": city, "latest": "unknown"}


# 通过path parameters传递文件路径
@chapter01.get('/files/{file_path:path}')
def filepath(file_path: str):
    return f"the file path is {file_path}"


@chapter01.get('/path_valid/{num}')
def path_params_validate(
    num: int = Path(..., title="your number", description="不可描述", ge=1, le=10)
):
    return num


""" Query Parameters and String Validations 查询参数和字符串验证"""
@chapter01.get("/query")
def page_limit(page: int = 1, limit: Optional[int] = None):
    if limit:
        return {"page": page, "limit": limit}
    return {"page": page}


@chapter01.get("/query/bool/conversion")
def type_conversion(param: bool = False):
    return param


# 多个查询参数的列表，参数别名
@chapter01.get("/query/validations")
def query_params_validate(
    value: str = Query(..., min_length=8, max_length=10,regex="^a"),
    values: List[str] = Query(default=["v1", "v2"], alias="alias_name")
):
    return value, values


"""Request Body Fields 请求体和字段"""
class CityInfo(BaseModel):
    name: str = Field(..., example="Beijing", )
    country: str
    country_code: str = None
    country_population: int = Field(default=800, title="人口数量", description="国家人口数量", ge=800)
    class Config:
        schema_extra = {
            "example": {
                "name": "Shanghai",
                "country": "China",
                "country_code": "CN",
                "country_population": 1400000000,

            }
        }
@chapter01.post('/request_body/city')
def city_info(city: CityInfo):
    return city.dict()


"""Request Body + Query Parameters and String Validations 参数混合 """

@chapter01.put('/request_body/city/{name}')
def mix_city_info(
    name: str,
    city01: CityInfo,
    city02: CityInfo,
    confirmed: int = Query(ge=0, description="确认数", default=0),
    death: int = Query(ge=0, description="死亡数", default=0)
):
    if name == "Shanghai":
        return {"Shanghai": {"confirmed": confirmed, "death": death}}
    return city01.dict(), city02.dict()

"""Request Body - Nested Models 数据格式嵌套请求体"""
class Data(BaseModel):
    city: List[CityInfo] = None
    date: date
    confirmed: int = Query(ge=0, description="确认数", default=0)
    death: int = Query(ge=0, description="死亡数", default=0)
    recovered: int = Query(ge=0, description="治愈数", default=0)

@chapter01.put('request_body/nested')
def nested_models(data: Data):
    return data

""" Cookie and Header 参数"""

@chapter01.get('/cookie')
def cookie(cookie_id: Optional[str] = Cookie(None)):
    return {"cookie_id": cookie_id}

@chapter01.get('/header')
def header(user_agent: Optional[str] = Header(None, convert_underscores=True), x_token: List[str] = Header(None)):
    """
    有些http代理和服务器是不允许请求头中带有下划线的，convert_underscores=True会把user_agent转成user-agent
    :param user_agent:
    :param x_token:
    :return:
    """
    return {"User-Agent": user_agent, "x_token": x_token}
